package com.vogue.flowmeter.update;

import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;
import androidx.core.content.FileProvider;
import com.vogue.flowmeter.api.event.DownloadMessageEvent;
import com.vogue.flowmeter.api.retrofit.NetWorkManager;
import org.greenrobot.eventbus.EventBus;
import java.io.File;
import okhttp3.ResponseBody;
import retrofit2.Call;

/**
 * 下载器  下载apk和其他文件
 */

public class DownloadService extends Service {

    private static final String TAG = "DownloadService";

    private static VogueDownLoadBinder vogueDownLoadBinder;
    private boolean apk=false;
    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public IBinder onBind(Intent intent) {
        vogueDownLoadBinder = new VogueDownLoadBinder();
        return vogueDownLoadBinder;
    }

    public class VogueDownLoadBinder extends Binder {


        /**
         * 开始下载
         *
         * @param url      下载链接
         * @param isApk    是不是apk
         * @param destFileName 文件名称
         */
        public void startDownload(String url, String destFileName, boolean isApk) {
            apk=isApk;
            NetWorkManager.getInstance().getDownloadBleApiService().download(url).enqueue(new FileCallBack(DownloadService.this,destFileName) {
                @Override
                public void onSuccess(File file, Progress progress) {
                    Log.e(TAG,"AbsolutePath："+file.getAbsoluteFile().getAbsolutePath());
                    Log.e(TAG,"progress.status："+progress.status);
                    cancelDownload();
                    //下载完毕时 , 发送事件
                    if (progress.status== Progress.FINISH){
                        DownloadMessageEvent download=new DownloadMessageEvent();
                        download.setControl(TAG);
                        download.setApk(apk);
                        download.setProgress(100);
                        download.setMessage("下载完毕");
                        download.setStatus(true);
                        EventBus.getDefault().post(download);
                    }
                    if (apk&&progress.status== Progress.FINISH){
                        startInstallApk(progress.filePath);
                    }


                }

                @Override
                public void onProgress(Progress progress) {
                    Log.e(TAG,"文件总大小:"+progress.totalSize);
                    Log.e(TAG,"当前下载量:"+progress.downloadedSize);
                    Log.e(TAG,"下载进度:"+((float)progress.downloadedSize/(float)progress.totalSize));

                    int percent = (int) (((float)progress.downloadedSize/(float)progress.totalSize) * 100);

                    DownloadMessageEvent download=new DownloadMessageEvent();
                    download.setControl(TAG);
                    download.setApk(apk);
                    download.setProgress(percent);
                    download.setTotalSize(progress.totalSize);
                    download.setDownloadedSize(progress.downloadedSize);
                    download.setMessage("正在下载");
                    download.setStatus(false);
                    EventBus.getDefault().post(download);
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {

                }
            });
        }
        /**
         * 开始下载（指定文件夹）
         *
         * @param url      下载链接
         * @param isApk    是不是apk
         * @param destFileName 文件名称
         */
        public void startDownload(String url, String destFileDir,String destFileName, boolean isApk) {
            apk=isApk;
            NetWorkManager.getInstance().getDownloadBleApiService().download(url).enqueue(new FileCallBack(destFileDir,destFileName) {
                @Override
                public void onSuccess(File file, Progress progress) {
                    Log.e(TAG,"AbsolutePath："+file.getAbsoluteFile().getAbsolutePath());
                    Log.e(TAG,"progress.status："+progress.status);
                    //下载完毕时 , 发送事件

                    cancelDownload();

                    if (progress.status== Progress.FINISH){
                        DownloadMessageEvent download=new DownloadMessageEvent();
                        download.setControl(TAG);
                        download.setApk(apk);
                        download.setProgress(100);
                        download.setTotalSize(progress.totalSize);
                        download.setDownloadedSize(progress.downloadedSize);
                        download.setMessage("下载完毕");
                        download.setStatus(true);
                        EventBus.getDefault().post(download);
                    }
                    if (apk&&progress.status== Progress.FINISH){
                        startInstallApk(progress.filePath);
                    }

                }

                @Override
                public void onProgress(Progress progress) {
                    Log.e(TAG,"文件总大小:"+progress.totalSize);
                    Log.e(TAG,"当前下载量:"+progress.downloadedSize);
                    Log.e(TAG,"下载进度:"+((float)progress.downloadedSize/(float)progress.totalSize));

                    int percent = (int) (((float)progress.downloadedSize/(float)progress.totalSize) * 100);

                    DownloadMessageEvent download=new DownloadMessageEvent();
                    download.setControl(TAG);
                    download.setApk(apk);
                    download.setProgress(percent);
                    download.setTotalSize(progress.totalSize);
                    download.setDownloadedSize(progress.downloadedSize);
                    download.setMessage("正在下载");
                    download.setStatus(false);
                    EventBus.getDefault().post(download);
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    t.printStackTrace();
                }
            });
        }
        /**
         * 取消下载
         */
        public void cancelDownload() {
            DownloadMessageEvent download=new DownloadMessageEvent();
            download.setControl(TAG);
            download.setApk(apk);
            download.setProgress(0);
            download.setTotalSize(0);
            download.setDownloadedSize(0);
            download.setMessage("下载取消");
            download.setStatus(true);
            EventBus.getDefault().post(download);
        }
    }




    @Override
    public void onTaskRemoved(Intent rootIntent) {
        if (vogueDownLoadBinder != null) {
            vogueDownLoadBinder.cancelDownload();
        }
        super.onTaskRemoved(rootIntent);
        this.stopSelf();
    }



    /**
     * 下载完毕 , 安装新的Apk
     */
    private void startInstallApk(String filePath) {
        vogueDownLoadBinder.cancelDownload();
        //apk文件的本地路径
        File apkfile = new File(filePath);
        //会根据用户的数据类型打开android系统相应的Activity。
        Intent intent = new Intent(Intent.ACTION_VIEW);
        //设置intent的数据类型是应用程序application
        //判读版本是否在7.0以上
        if (Build.VERSION.SDK_INT >= 24) {
            Uri apkUri = FileProvider.getUriForFile(this, getPackageName() + ".fileprovider", apkfile);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            //为这个新apk开启一个新的activity栈
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
        }
        //开始安装
        startActivity(intent);
        //关闭旧版本的应用程序的进程
        android.os.Process.killProcess(android.os.Process.myPid());
    }


}
